// 数独游戏逻辑
const difficultyLevels = {
    easy: 50, // 简单难度 - 显示50个数字
    medium: 40, // 中等难度 - 显示30个数字
    hard: 25 // 偏难难度 - 显示25个数字
};

let sudokuBoard = [];
let solutionBoard = [];
let selectedCell = null;
let currentDifficulty = '';
let errorCount = 0;
let winStreak = 0;

document.addEventListener('DOMContentLoaded', () => {
    // 难度选择按钮事件
    document.querySelectorAll('.difficulty-btn').forEach(btn => {
        btn.addEventListener('click', () => {
            currentDifficulty = btn.dataset.difficulty;
            document.querySelector('.difficulty-select').classList.add('hidden');
            document.querySelector('.game-container').classList.remove('hidden');
            initGame();
        });
    });

    // 重新开始按钮事件
    document.querySelector('.restart-btn').addEventListener('click', () => {
        initGame();
    });
});

function initGame() {
    // 重置游戏状态
    errorCount = 0;
    if (errorCount >= 3) {
        winStreak = 0;
        updateWinStreakDisplay();
    }
    document.querySelectorAll('.heart').forEach(heart => {
        heart.classList.remove('white');
    });

    generateSudoku();
    renderBoard();
    updateNumberCounts();
}

function generateSudoku() {
    // 生成完整解
    solutionBoard = generateSolution();

    // 根据难度创建游戏板
    sudokuBoard = JSON.parse(JSON.stringify(solutionBoard));
    const cellsToHide = 81 - difficultyLevels[currentDifficulty];

    let hiddenCells = 0;
    while (hiddenCells < cellsToHide) {
        const row = Math.floor(Math.random() * 9);
        const col = Math.floor(Math.random() * 9);

        if (sudokuBoard[row][col] !== 0) {
            sudokuBoard[row][col] = 0;
            hiddenCells++;
        }
    }
}

function generateSolution() {
    // 生成有效的数独解
    const board = Array(9).fill().map(() => Array(9).fill(0));

    // 填充对角线上的3x3方块
    for (let box = 0; box < 9; box += 3) {
        fillBox(board, box, box);
    }

    // 解数独
    solveSudoku(board);
    return board;
}

function fillBox(board, row, col) {
    const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];
    shuffleArray(nums);

    let index = 0;
    for (let i = 0; i < 3; i++) {
        for (let j = 0; j < 3; j++) {
            board[row + i][col + j] = nums[index++];
        }
    }
}

function solveSudoku(board) {
    for (let row = 0; row < 9; row++) {
        for (let col = 0; col < 9; col++) {
            if (board[row][col] === 0) {
                for (let num = 1; num <= 9; num++) {
                    if (isValid(board, row, col, num)) {
                        board[row][col] = num;
                        if (solveSudoku(board)) {
                            return true;
                        }
                        board[row][col] = 0;
                    }
                }
                return false;
            }
        }
    }
    return true;
}

function isValid(board, row, col, num) {
    // 检查行
    for (let x = 0; x < 9; x++) {
        if (board[row][x] === num) {
            return false;
        }
    }

    // 检查列
    for (let x = 0; x < 9; x++) {
        if (board[x][col] === num) {
            return false;
        }
    }

    // 检查3x3方块
    const boxRow = Math.floor(row / 3) * 3;
    const boxCol = Math.floor(col / 3) * 3;

    for (let i = 0; i < 3; i++) {
        for (let j = 0; j < 3; j++) {
            if (board[boxRow + i][boxCol + j] === num) {
                return false;
            }
        }
    }

    return true;
}

function updateWinStreakDisplay() {
    const streakElement = document.querySelector('.win-streak');
    if (streakElement) {
        streakElement.textContent = `连胜: ${winStreak}`;
    }
}

function updateNumberCounts() {
    // 统计每个数字剩余需要填的数量
    const counts = Array(9).fill(9);

    for (let row = 0; row < 9; row++) {
        for (let col = 0; col < 9; col++) {
            if (sudokuBoard[row][col] !== 0) {
                counts[sudokuBoard[row][col] - 1]--;
            }
        }
    }

    // 更新UI显示
    const container = document.querySelector('.number-counts-container');
    container.innerHTML = '';

    for (let i = 0; i < 9; i++) {
        if (counts[i] > 0) {
            const countElement = document.createElement('div');
            countElement.className = 'number-count';
            countElement.innerHTML = `${i + 1}<sup>${counts[i]}</sup>`;
            countElement.addEventListener('click', () => handleNumberCountClick(i + 1, countElement));
            container.appendChild(countElement);
        }
    }
}

function isGameComplete() {
    // 检查游戏是否完成
    for (let row = 0; row < 9; row++) {
        for (let col = 0; col < 9; col++) {
            if (sudokuBoard[row][col] === 0) {
                return false;
            }
        }
    }
    return true;
}

function showSuccessModal() {
    // 显示成功提示框
    winStreak++;
    updateWinStreakDisplay();
    const modal = document.querySelector('.success-modal');
    modal.classList.remove('hidden');

    // 退出游戏按钮
    document.querySelector('.success-btn.exit').addEventListener('click', () => {
        modal.classList.add('hidden');
        document.querySelector('.game-container').classList.add('hidden');
        document.querySelector('.difficulty-select').classList.remove('hidden');
    });
    // 继续游戏按钮
    document.querySelector('.success-btn.continue').addEventListener('click', () => {
        modal.classList.add('hidden');
        initGame(); // 重新开始游戏
    });
}

function renderBoard() {
    const grid = document.querySelector('.sudoku-grid');
    grid.innerHTML = '';

    for (let row = 0; row < 9; row++) {
        for (let col = 0; col < 9; col++) {
            const cell = document.createElement('div');
            cell.className = 'cell';

            if (sudokuBoard[row][col] !== 0) {
                cell.textContent = sudokuBoard[row][col];
                cell.classList.add('fixed', 'has-number');
            }
            cell.addEventListener('click', () => handleCellClick(row, col, cell));
            grid.appendChild(cell);
        }
    }
}

function handleCellClick(row, col, cell) {
    // 清除之前的选择和错误标记
    clearHighlights();
    if (sudokuBoard[row][col] !== 0) {
        num = sudokuBoard[row][col];
        const cells = document.querySelectorAll('.cell');
        cells.forEach(c => {
            if (c.textContent === num.toString()) {
                c.classList.add('highlight-number');
            }
        });
    } else {
        selectedCell = { row, col, element: cell };
        cell.classList.add('selected');

        // 高亮所在行、列和3x3宫格
        highlightRelatedCells(row, col);

        // 处理键盘输入
        document.addEventListener('keydown', handleKeyPress);
    }
}


function handleNumberCountClick(num, countElement) {
    // 清除之前的选择和错误标记
    clearHighlights();
    const cells = document.querySelectorAll('.cell');
    cells.forEach(c => {
        if (c.textContent === num.toString()) {
            c.classList.add('highlight-number');
        }
    });
    countElement.classList.add('highlight-number');
}

function highlightRelatedCells(row, col) {
    // 高亮行
    for (let c = 0; c < 9; c++) {
        const cell = document.querySelector(`.sudoku-grid > .cell:nth-child(${row * 9 + c + 1})`);
        if (cell) cell.classList.add('highlight-row');
    }

    // 高亮列
    for (let r = 0; r < 9; r++) {
        const cell = document.querySelector(`.sudoku-grid > .cell:nth-child(${r * 9 + col + 1})`);
        if (cell) cell.classList.add('highlight-col');
    }

    // 高亮3x3宫格
    const boxRow = Math.floor(row / 3) * 3;
    const boxCol = Math.floor(col / 3) * 3;

    for (let r = boxRow; r < boxRow + 3; r++) {
        for (let c = boxCol; c < boxCol + 3; c++) {
            const cell = document.querySelector(`.sudoku-grid > .cell:nth-child(${r * 9 + c + 1})`);
            if (cell) cell.classList.add('highlight-box');
        }
    }
}

function handleKeyPress(e) {
    if (!selectedCell) return;

    const { row, col, element } = selectedCell;

    if (e.key >= '1' && e.key <= '9') {
        const num = parseInt(e.key);

        // 更新数字统计
        if (num === solutionBoard[row][col]) {
            sudokuBoard[row][col] = num;
            element.textContent = num;
            element.classList.add('fixed', 'has-number');
            updateNumberCounts();

            // 清除原有高亮并高亮相同数字
            clearHighlights();
            document.querySelectorAll('.cell').forEach(c => {
                if (c.textContent === num.toString()) {
                    c.classList.add('highlight-number');
                }
            });

            // 检查是否完成
            if (isGameComplete()) {
                showSuccessModal();
            }
        } else {
            errorCount++;
            element.classList.add('error');

            // 更新红心显示
            const hearts = document.querySelectorAll('.heart');
            if (errorCount <= hearts.length) {
                hearts[errorCount - 1].classList.add('white');
            }

            if (errorCount >= 3) {
                alert('机会已用光，游戏将重新开始！');
                errorCount = 0;
                // 重置红心
                document.querySelectorAll('.heart').forEach(heart => {
                    heart.classList.remove('white');
                });
                initGame();
            } else {
                setTimeout(() => {
                    element.classList.remove('error');
                }, 1000);
            }
        }

        // 移除键盘事件监听
        document.removeEventListener('keydown', handleKeyPress);
        selectedCell = null;
    } else if (e.key === 'Backspace' || e.key === 'Delete') {
        // 清除单元格
        if (!element.classList.contains('fixed')) {
            sudokuBoard[row][col] = 0;
            element.textContent = '';
        }
    }
}


function clearHighlights() {
    document.querySelectorAll('.cell').forEach(c => {
        c.classList.remove('selected', 'error', 'highlight-row', 'highlight-col', 'highlight-box', 'highlight-number');
    });
    document.querySelectorAll('.number-count').forEach(c => {
        c.classList.remove('selected', 'error', 'highlight-row', 'highlight-col', 'highlight-box', 'highlight-number');
    });
}

function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
}